//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖保佑             永无BUG 
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//                  不见满街漂亮妹，哪个归得程序员？  


/* ****************************************************************************
 * Author: 671643387
 * Date: 2015/9/14
 * ***************************************************************************/

var fs = require('fs');
var ServerManager = require('../js/servers.js').ServerManager;

var gServers = new ServerManager();
var gMysqlPool = require('./pool.js');

function main() {
    if (process.argv.length < 3) {
        return false;
    }

    var openidfiledir = process.argv[2];   // OPENID文件目录

    console.log("start process directory " + openidfiledir);

    async.series([
        function (cb) {
            gServers.load({slave:true, native:true}, function(err) {
                cb(err);
            });
        },
        function(cb) {
            gMysqlPool.init("login", function(err) {
                cb(err);
            });
        },
        function(cb) {
            var fileList = [];
            var dirList = fs.readdirSync(openidfiledir);
            dirList.forEach(function(item){
                if (!fs.statSync(openidfiledir + "/" + item).isDirectory()) {
                    fileList.push(item);
                }
            });

            async.eachSeries(fileList, function(file, esCb){
                processFile(openidfiledir + "/" + file, function(){
                    esCb(null);
                });
            }, function(err){
                cb(null);
            });
        }
    ], function(err) {
        console.log("finish");
        process.exit(0);
    });
}

main();

function processFile(strFilename, fn){

    console.log("================ process " + strFilename);

    var openids = [];                   // 需要更新的OPENID数组
    var openidTimes = {};               // OPENID时间

    async.series([
        function(cb) {
            var data = fs.readFileSync(strFilename, 'UTF-8');
            openids = data.split('\n');
            openids.forEach(function(openid){
                if (openid != '') {
                    openidTimes[openid] = {
                        reg_time: 0,
                        login_time: 0
                    };
                }
            });
            console.log(openids.length + " openid");
            cb(null);
        },
        function(cb) {
            async.each(gServers.getSids(), function(sid, asecb) {
                var db = gServers.getGameDB(sid);
                if (!db) {
                    console.log(sid + " db error");
                    asecb();
                    return;
                }

                var uids = [];  // 这个服务器要查询的人的所有UID
                var uidMap = {};
                async.series([
                    function(icb){
                        // 更新这个人的注册时间
                        db.collection('plat').find({_id:{"$in":openids}}).toArray(function(err, res){
                            if (err) {
                                console.error(sid + " plat failed");
                                icb(err);
                            } else {
                                res.forEach(function(plat){
                                    var platTime = +plat.time;
                                    var oldTime = +openidTimes[plat._id]["reg_time"];

                                    if ((isNaN(oldTime) || oldTime == 0) || (platTime < oldTime)) {
                                        openidTimes[plat._id]["reg_time"] = platTime;
                                    }

                                    var oldLoginTime = +openidTimes[plat._id]["login_time"];
                                    if ((isNaN(oldLoginTime) || oldLoginTime == 0) || (platTime > oldLoginTime)) {
                                        openidTimes[plat._id]["login_time"] = platTime;
                                    }

                                    uidMap[plat.uid] = plat._id;
                                    uids.push(plat.uid);
                                    if (plat.uids) {
                                        plat.uids.forEach(function(uid){
                                            uids.push(uid);
                                            uidMap[uid] = plat._id;
                                        });
                                    }
                                });
                                icb(null);
                            }
                        });
                    },

                    function(icb) {
                        // 更新最后登录时间
                        db.collection('user').find({_id:{"$in":uids}}, {'mark.day':1}).toArray(function(err, res){
                            if (err) {
                                console.error(sid + " user failed");
                                icb(err);
                            } else {
                                res.forEach(function(user){
                                    var uid = user._id;
                                    var lastLoginTime = convertStringToTimeStamp(user.mark.day);

                                    var uropenid = uidMap[uid];
                                    if (lastLoginTime > openidTimes[uropenid]['login_time']) {
                                        openidTimes[uropenid]["login_time"] = lastLoginTime;
                                    }
                                });
                                icb(null);
                            }
                        });
                    }
                ], function(err){
                    asecb(null);
                });
            }, function(err){
                cb(null);
            });
        },
        function(cb){
            console.log("collect complete, writing to mysql");

            async.each(Object.keys(openidTimes), function(openid, asecb){
                var reg_time = openidTimes[openid]['reg_time'];
                var login_time = openidTimes[openid]['login_time'];

                var SQL = gMysqlPool.format("UPDATE login SET reg_time=?, login_time=? WHERE openid=?;",
                    [ reg_time, login_time, openid ]);

                gMysqlPool.query(SQL, function(err, res){
                    if (err) {
                        console.log(err);
                    }
                    asecb(null);
                });
            }, function(err){
                cb(null);
            });
        }
    ], function(err) {
        console.log("================ finish process file " + strFilename);
        fn();
    });
}

function convertStringToTimeStamp(strDate) {
    try {
        strDate += '';
        var year = +(strDate.substring(0, 4));
        var month = +(strDate.substring(4, 6));
        var day = +(strDate.substring(6));
        if (isNaN(year) || isNaN(month) || isNaN(day)) {
            return 0;
        }
        return (new Date(year + "/" + month + "/" + day + " 00:00:00")).getTime() / 1000;
    } catch (e) {
        return 0;
    }
}